/**
 * Copyright &copy; 2012-2014 hongsuan.pplive All rights reserved.
 */
package com.hongsuan.pplive.modules.sys.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cnjson.common.beanvalidator.BeanValidators;
import com.cnjson.common.config.Global;
import com.cnjson.db.persistence.Page;
import com.cnjson.common.utils.DateUtils;
import com.cnjson.common.utils.StringUtils;
import com.cnjson.common.web.BaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.hongsuan.pplive.common.utils.excel.ExportExcel;
import com.hongsuan.pplive.common.utils.excel.ImportExcel;
import com.hongsuan.pplive.mobileAPI.utils.UploadFileUtils;
import com.hongsuan.pplive.modules.live.entity.LiveIncomeStrategy;
import com.hongsuan.pplive.modules.live.entity.LiveRechargeRecord;
import com.hongsuan.pplive.modules.live.service.LiveIncomeStrategyService;
import com.hongsuan.pplive.modules.live.service.LiveRechargeRecordService;
import com.hongsuan.pplive.modules.sys.entity.Role;
import com.hongsuan.pplive.modules.sys.entity.User;
import com.hongsuan.pplive.modules.sys.service.SystemService;
import com.hongsuan.pplive.modules.sys.utils.UserUtils;

/**
 * 用户Controller
 * 
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;

	@Autowired
	private LiveIncomeStrategyService liveIncomeStrategyService;

	@Autowired
	private LiveRechargeRecordService liveRechargeRecordService;

	@ModelAttribute
	public User get(@RequestParam(required = false) String id) {
		User userInfo = null;
		if (StringUtils.isNotBlank(id)) {
			userInfo = systemService.getUser(id);
		}
		if (userInfo == null) {
			return new User();
		}
		return userInfo;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "index" })
	public String index(User user, Model model) {
		return "modules/sys/userIndex";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "list", "" })
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		model.addAttribute("page", page);
		String userType = request.getParameter("userType");
		if (StringUtils.isEmpty(userType)) {
			return "modules/sys/userList";
		} else {
			return "modules/sys/anchorUserList";
		}
	}

	/// userAccountList
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "userAccountList")
	public String userAccountList(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		model.addAttribute("goldRate", Global.moneyConvertor);
		model.addAttribute("page", page);
		return "modules/sys/userAccountList";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "userAccountForm")
	public String userAccountform(User user, Model model) {
		model.addAttribute("user", user);
		model.addAttribute("goldRate", Global.moneyConvertor);
		return "modules/sys/userAccountForm";
	}

	// anchorUserlistL
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "anchorUserList")
	public String anchorUserlist(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findAnchorUser(new Page<User>(request, response), user);
		model.addAttribute("page", page);
		return "modules/sys/anchorUserList";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "anchorUserForm")
	public String anchorUserform(User user, Model model) {
		model.addAttribute("user", user);
		return "modules/sys/anchorUserForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "userAccountSave")
	public String userAccountSave(User user, HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) {
		systemService.updateUserAccount(user);
		addMessage(redirectAttributes, "修改账号'" + user.getLoginName() + "'成功");
		return "redirect:" + adminPath + "/sys/user/userAccountList?repage";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "userAccountConvert")
	public String userAccountConvert(@RequestParam("id") String id, RedirectAttributes redirectAttributes) {
		// LiveRechargeRecord recharge = liveRechargeRecordService.get(id);
		User user = UserUtils.get(id);
		if (user != null) {
			if (user.getAccount() > 0) {
				user.setGold(user.getGold() + (int) (user.getAccount() * Global.moneyConvertor));
				user.setAccount(0f);
				systemService.updateUserAccount(user);
				addMessage(redirectAttributes, "转为金豆成功!");
			} else {
				addMessage(redirectAttributes, "余额不足不能转为金豆!");
			}
		} else {
			addMessage(redirectAttributes, "找不到对应用户!");
		}

		return "redirect:" + adminPath + "/sys/user/userAccountList?repage";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping("userRecharge")
	public @ResponseBody String userRecharge(@RequestParam("userId") String userId,
			@RequestParam("amount") Float amount,
			@RequestParam(value = "checkGold", required = false, defaultValue = "0") String checkGold) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", Global.SUCCESS);
		try {
			User user = UserUtils.get(userId);
			LiveRechargeRecord recharge = new LiveRechargeRecord();
			recharge.setAmount(user.getAccount());
			recharge.setType(10);
			recharge.setRemarks("后台手工充值");
			recharge.setCreateBy(userId);
			recharge.setCreateById(userId);
			recharge.setState(1);
			recharge.setCreateDate(new Date());
			liveRechargeRecordService.save(recharge);
			if (checkGold.equals("1")) {
				user.setGold(user.getGold() + (int) (amount * Global.moneyConvertor));
			} else {
				user.setAccount(user.getAccount() + amount);
			}
			systemService.updateUserAccount(user);
		} catch (Exception e) {
			map.put("status", Global.FAILED);
			logger.error("充值失值", e);
		}
		Gson gson = new Gson();
		return gson.toJson(map);
	}

	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "listData" })
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		return page;
	}

	@RequestMapping(value = "userPictureList")
	public String userPictureList(@RequestParam("userId") String userId, Model model, HttpServletRequest request) {
		String basePath = UploadFileUtils.UPLOAD_REALPATH + File.separator + userId + File.separator + "album";
		String path = request.getSession().getServletContext().getRealPath(basePath);
		File file = new File(path);
		List<String> picFiles = new ArrayList<String>();
		if (file.isDirectory()) {
			File[] fileList = file.listFiles();
			if (fileList != null) {
				for (File fi : fileList) {
					String name = fi.getName();
					System.out.println("file name------------>" + name);
					if (StringUtils.isEmpty(name)) {
						continue;
					}
					if (UploadFileUtils.isPicture(name)) {
						picFiles.add(basePath + File.separator + fi.getName());
					}
				}
			}
		}
		model.addAttribute("userId", userId);
		model.addAttribute("fileList", picFiles);
		return "modules/sys/anchorUserPictureList";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping("anchorAudit")
	public @ResponseBody String anchorAudit(@RequestParam("userId") String userId,
			@RequestParam("status") Integer status) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", Global.SUCCESS);
		try {
			User user = UserUtils.get(userId);
			user.setAuthenStatus(status);
			if (status == 2) {
				user.setUserType("1");
				LiveIncomeStrategy strategy = new LiveIncomeStrategy();
				strategy.setPercentage(Global.presentRate);
				strategy.setUserId(userId);
				strategy.setCreateBy(userId);
				liveIncomeStrategyService.save(strategy);
			}
			systemService.saveUser(user);
		} catch (Exception e) {
			map.put("status", Global.FAILED);
			logger.error("主播审核失败", e);
		}
		Gson gson = new Gson();
		return gson.toJson(map);
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		model.addAttribute("user", user);
		model.addAttribute("allRoles", systemService.findAllRole());
		return "modules/sys/userForm";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if ((systemService.getUser(user.getId()) == null)
				&& (StringUtils.isNoneEmpty(user.getNewPassword()) || "".equalsIgnoreCase(user.getNewPassword()))) {
			user.setPassword(SystemService.entryptPassword("123456"));
		}

		if (!beanValidator(model, user)) {
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))) {
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()) {
			if (roleIdList.contains(r.getId())) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			UserUtils.clearCache();
			// UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if (UserUtils.getUser().getId().equals(user.getId())) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
		} else if (UserUtils.isAdmin()) {
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		} else {
			systemService.deleteUser(user);
			addMessage(redirectAttributes, "删除用户成功");
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 导出用户数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(User user, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
			new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 导入用户数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list) {
				try {
					if ("true".equals(checkLoginName("", user.getLoginName()))) {
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					} else {
						failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * 
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			User user = new User();
			user.setId("导入时请删除此行：用户ID");
			user.setName("昵称");
			user.setRemarks("备注");
			user.setLoginName("用户登录名");
			user.setCreateDate(new Date());

			List<User> list = Lists.newArrayList();
			list.add(user);
			new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 验证登录名是否有效
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName != null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 用户信息显示及保存
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getName())) {
			currentUser.setRemarks(user.getRemarks());
			currentUser.setPhoto(user.getPhoto());
			systemService.updateUserInfo(currentUser);
			model.addAttribute("message", "保存用户信息成功");
		}
		model.addAttribute("user", currentUser);
		model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
	}

	/**
	 * 返回用户信息
	 * 
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}

	/**
	 * 修改个人用户密码
	 * 
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
			if (SystemService.validatePassword(oldPassword, user.getPassword())) {
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			} else {
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		User user = UserUtils.getUser();
		List<User> list = systemService.findAllUser(user);
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_" + e.getId());
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}

	// @InitBinder
	// public void initBinder(WebDataBinder b) {
	// b.registerCustomEditor(List.class, "roleList", new
	// PropertyEditorSupport(){
	// @Autowired
	// private SystemService systemService;
	// @Override
	// public void setAsText(String text) throws IllegalArgumentException {
	// String[] ids = StringUtils.split(text, ",");
	// List<Role> roles = new ArrayList<Role>();
	// for (String id : ids) {
	// Role role = systemService.getRole(Long.valueOf(id));
	// roles.add(role);
	// }
	// setValue(roles);
	// }
	// @Override
	// public String getAsText() {
	// return Collections3.extractToString((List) getValue(), "id", ",");
	// }
	// });
	// }
}
